package com.itmei.exceldemo.controller;

import com.itmei.exceldemo.domain.UserInfo;
import com.itmei.exceldemo.result.ResultData;
import com.itmei.exceldemo.utils.EasyExcelUtils;
import com.itmei.exceldemo.utils.UserBuildUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @Author itmei
 * @Date 2024/4/13 21:30
 * @description: 用户详情控制层
 * @Title: UserInfoController
 * @Package com.itmei.exceldemo.controller
 */
@RestController
public class UserInfoController {
    @GetMapping("userInfo/excelExport")
    public ResultData userInfoExcelExport() {
        List<UserInfo> userInfoList = getUserInfoList();
        EasyExcelUtils.download("用户列表", userInfoList);
        return ResultData.success();
    }

    public List<UserInfo> getUserInfoList() {
        List<UserInfo> userInfoList = new ArrayList<>();
        List<String> sexStrList = Arrays.asList("男", "女");
        Random sexRandom = new Random();
        for (int i = 0; i < 10; i++) {
            UserInfo userInfo = new UserInfo();
            String sexStr = sexStrList.get(sexRandom.nextInt(sexStrList.size()));
            userInfo.setSex(sexStr);
            String name = UserBuildUtils.buildName(sexStr);
            userInfo.setName(name);
            userInfo.setAge(RandomUtils.nextInt(18, 35));
            userInfo.setPhone(UserBuildUtils.generatePhoneNumber());
            userInfoList.add(userInfo);
        }
        return userInfoList;
    }

    @PostMapping("userInfo/excelImport")
    public ResultData userInfoExcelImport(@RequestParam("file") MultipartFile file) throws IOException {
        //解析导入的excel文件成对象
        List<UserInfo> userInfoList = EasyExcelUtils.readExcel(UserInfo.class, file.getInputStream());
        //处理对象
        System.out.println(userInfoList);
        return ResultData.success();
    }
}
